import { defineStore } from 'pinia';
import { 
  getPrompts, getPromptDetail, createPrompt, updatePrompt, 
  deletePrompt, copyPrompt, batchDeletePrompts, getPromptStats,
  getTags, getAIModels
} from '../api/prompts';

export const usePromptStore = defineStore('prompt', {
  state: () => ({
    prompts: [],
    currentPrompt: null,
    tags: [],
    aiModels: [],
    stats: null,
    loading: false,
    error: null,
    totalPrompts: 0,
    filters: {
      search: '',
      tags: [],
      aiModel: null,
      sort: '-updated_at'
    }
  }),
  
  getters: {
    getPromptById: (state) => (id) => {
      return state.prompts.find(prompt => prompt.id === id);
    }
  },
  
  actions: {
    async fetchPrompts(params = {}) {
      this.loading = true;
      try {
        // 合并过滤条件
        const queryParams = {
          search: this.filters.search,
          ordering: this.filters.sort,
          ...params
        };
        
        if (this.filters.tags.length > 0) {
          queryParams.tags = this.filters.tags.join(',');
        }
        
        if (this.filters.aiModel) {
          queryParams.ai_model = this.filters.aiModel;
        }
        
        const response = await getPrompts(queryParams);
        this.prompts = response.results || response;
        this.totalPrompts = response.count || response.length;
        return response;
      } catch (error) {
        this.error = '获取提示词列表失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    async fetchPromptDetail(id) {
      this.loading = true;
      try {
        const prompt = await getPromptDetail(id);
        this.currentPrompt = prompt;
        return prompt;
      } catch (error) {
        this.error = '获取提示词详情失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    async createNewPrompt(promptData) {
      this.loading = true;
      try {
        const prompt = await createPrompt(promptData);
        this.prompts.unshift(prompt);
        return prompt;
      } catch (error) {
        this.error = '创建提示词失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    async updateExistingPrompt(id, promptData) {
      this.loading = true;
      try {
        const updatedPrompt = await updatePrompt(id, promptData);
        const index = this.prompts.findIndex(p => p.id === id);
        if (index !== -1) {
          this.prompts[index] = updatedPrompt;
        }
        if (this.currentPrompt && this.currentPrompt.id === id) {
          this.currentPrompt = updatedPrompt;
        }
        return updatedPrompt;
      } catch (error) {
        this.error = '更新提示词失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    async removePrompt(id) {
      this.loading = true;
      try {
        await deletePrompt(id);
        this.prompts = this.prompts.filter(p => p.id !== id);
        if (this.currentPrompt && this.currentPrompt.id === id) {
          this.currentPrompt = null;
        }
      } catch (error) {
        this.error = '删除提示词失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    async copyExistingPrompt(id) {
      this.loading = true;
      try {
        const newPrompt = await copyPrompt(id);
        this.prompts.unshift(newPrompt);
        return newPrompt;
      } catch (error) {
        this.error = '复制提示词失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    async batchRemovePrompts(ids) {
      this.loading = true;
      try {
        await batchDeletePrompts(ids);
        this.prompts = this.prompts.filter(p => !ids.includes(p.id));
      } catch (error) {
        this.error = '批量删除提示词失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    async fetchPromptStats() {
      this.loading = true;
      try {
        const stats = await getPromptStats();
        this.stats = stats;
        return stats;
      } catch (error) {
        this.error = '获取提示词统计信息失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    async fetchTags(search = '') {
      try {
        const tags = await getTags(search);
        this.tags = tags;
        return tags;
      } catch (error) {
        this.error = '获取标签列表失败';
        throw error;
      }
    },
    
    async fetchAIModels() {
      try {
        const models = await getAIModels();
        this.aiModels = models;
        return models;
      } catch (error) {
        this.error = '获取AI模型列表失败';
        throw error;
      }
    },
    
    setFilters(filters) {
      this.filters = { ...this.filters, ...filters };
    },
    
    clearFilters() {
      this.filters = {
        search: '',
        tags: [],
        aiModel: null,
        sort: '-updated_at'
      };
    }
  }
});